import {Component} from 'react'
import Taro from "@tarojs/taro"
import userStore from "./store/userStore";
import './app.scss'

function getToken() {
  return new Promise(((resolve) => {
    userStore.getState(state => resolve(state.value?.token))
  }))
}


const interceptor = async function (chain) {
  const requestParams = chain.requestParams
  requestParams.header = {
    "Authorization": await getToken()
  }
  return chain.proceed(requestParams)
    .then(res => {
      if (res.data.code !== 200) {
        throw new Error(res.data.message)
      }
      return res.data
    }).catch((e) => {
      Taro.showToast(
        {
          title: e.message,
          icon: 'none',
          duration: 2000
        }
      )
      throw e;
    })
}
Taro.addInterceptor(interceptor)

class App extends Component {

  render() {
    return this.props.children
  }
}

// finally polyfill
Promise.prototype['finally'] = function finallyConstructor(callback) {
  var constructor = this.constructor;
  return this.then(
    function (value) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function () {
        return value;
      });
    },
    function (reason) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function () {
        // @ts-ignore
        return constructor.reject(reason);
      });
    }
  );
}
;


export default App
